package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"goods-mgr/model"
	"goods-mgr/orderrpc/internal/svc"
	"goods-mgr/orderrpc/orderrpc"
	"gorm.io/gorm"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *orderrpc.CartAddRequest) (*orderrpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line

	var order model.Order
	model.DB.Debug().Where("orderId=?", in.OrderId).Find(&order)
	if order.ID == 0 {

		return nil, fmt.Errorf("商品不存在")
	}
	if order.Num < in.Quantity {
		return nil, fmt.Errorf("商品库存不够")
	}
	cart := model.Cart{
		Model: gorm.Model{
			ID: uint(in.CartId),
		},
		OrderId:  int64(int(in.OrderId)),
		Quantity: int64(int(in.Quantity)),
		Selected: in.Selected,
	}
	if cart.OrderId == in.OrderId {

		return nil, fmt.Errorf("该商品已存在")
		//cart.Quantity += in.Quantity
	} else {
		cart = model.Cart{
			Model: gorm.Model{
				ID: uint(in.CartId),
			},
			OrderId:  int64(int(in.OrderId)),
			Quantity: int64(int(in.Quantity)),
			Selected: in.Selected,
		}
	}
	model.DB.Create(&cart)
	return &orderrpc.CartAddResponse{
		CardId: int64(cart.ID),
	}, nil
}
